﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;
using TouchToolkit.Framework;
using Framework.TouchInputProviders;
using System.Runtime.Serialization;
using ActiveStoryTouch.DataModel;
using System.Windows.Ink;
using System.Runtime.Serialization.Json;
using Microsoft.Windows.Controls.Ribbon;
using ActiveStoryTouch.UI.Enums;
using System.ComponentModel;
using ActiveStoryTouch.DataModel.Helpers;
using ActiveStoryTouch.UI.Helpers;
using ActiveStoryTouch.DataModel.Wpf;
using ActiveStoryTouch.UI.Dialogs;
using Microsoft.Win32;

namespace ActiveStoryTouch.UI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : RibbonWindow
    {
        private InterfaceStyle _currentInterfaceStyle;

        public SessionManager ActiveSessionManager { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            ActiveSessionManager = new SessionManager(this.PageInkCanvas);
            this.DataContext = ActiveSessionManager;
            PageInkCanvas.DefaultDrawingAttributes.FitToCurve = true;
            ICollectionView listView = CollectionViewSource.GetDefaultView(ActiveSessionManager.CurrentProject.PageDictionary.ValueObservableCollection);
            ListCollectionView listCollectionView = (ListCollectionView)listView;
            listCollectionView.CustomSort = new PageSorter();

            //ActiveSessionManager.CurrentProject.PageDictionary.Add(0, new DataModel.Page { PageNumber = 0, Name = "Test Page" });
            //ActiveSessionManager.CurrentProject.PageDictionary.Add(2, new DataModel.Page { PageNumber = 2, Name = "Second Test Page" });

            DragDropHandler ddh = new DragDropHandler(ButtonHotspotToolLabel, new DataObject("Button"));

            PageInkCanvas.EditingMode = InkCanvasEditingMode.Select;

            SetupObjectsPanel(ActiveSessionManager.CurrentPage);
            SetupEventsPanel();
        }

        private void SetupEventsPanel(PrototypeElement instance = null)
        {
            TriggersGrid.RowDefinitions.Clear();
            TriggersGrid.Children.Clear();
            if (instance == null)
                TriggersGrid.IsEnabled = false;
            else
                TriggersGrid.IsEnabled = true;

            const string behaviorLabelFormatBase = "Navigate, Page {0}";

            foreach (var item in ActiveSessionManager.CommonGestureManager.GestureList)
            {
                TriggersGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(32) });

                Border borderLeft = new Border { BorderBrush = Brushes.Gray, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5), Background = Brushes.White };
                Grid.SetRow(borderLeft, TriggersGrid.RowDefinitions.Count - 1);
                Grid.SetColumn(borderLeft, 0);
                Label gestureLabel = new Label { Content = item.DisplayName };
                borderLeft.Child = gestureLabel;
                TriggersGrid.Children.Add(borderLeft);

                Border borderRight = new Border { BorderBrush = Brushes.Gray, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5), Background = Brushes.White };
                Grid.SetRow(borderRight, TriggersGrid.RowDefinitions.Count - 1);
                Grid.SetColumn(borderRight, 1);
                DockPanel rightDockPanel = new DockPanel { LastChildFill = true };
                borderRight.Child = rightDockPanel;

                String behaviorLabelText = String.Empty;
                if (instance != null)
                {
                    if (instance.GestureTargetPageMap.ContainsKey(item.Identifier) && ActiveSessionManager.CurrentProject.PageDictionary.ContainsKey(instance.GestureTargetPageMap[item.Identifier]))
                        behaviorLabelText = String.Format(behaviorLabelFormatBase, ActiveSessionManager.CurrentProject.PageDictionary[instance.GestureTargetPageMap[item.Identifier]].PageNumber);
                }
                Label behaviorLabel = new Label { Content = behaviorLabelText };

                Button setValueButton = new Button { Content = "...", Width = 20, Tag = item };
                
                setValueButton.Click+=new RoutedEventHandler(delegate (object sender, RoutedEventArgs args)
                    {
                        if (instance == null) 
                            return;
                        String selectedGestureId = (setValueButton.Tag as Gesture).Identifier;
                        GestureTargetDialog gtd = new GestureTargetDialog(ActiveSessionManager);
                        if (!gtd.ShowDialog().GetValueOrDefault(false))
                        {
                            return;
                        }

                        instance.GestureTargetPageMap.Add(selectedGestureId, gtd.SelectedPage.UnqiueId);
                        behaviorLabel.Content = String.Format(behaviorLabelFormatBase, ActiveSessionManager.CurrentProject.PageDictionary[instance.GestureTargetPageMap[selectedGestureId]].PageNumber);
                    });

                DockPanel.SetDock(setValueButton, Dock.Right);
                rightDockPanel.Children.Add(setValueButton);
                rightDockPanel.Children.Add(behaviorLabel);
                TriggersGrid.Children.Add(borderRight);
            }
        }

        //ICollectionView listView = CollectionViewSource.GetDefaultView(wbfsDriveCurrent.EntriesOnDrive);
        //ListCollectionView listCollectionView = (ListCollectionView)listView;
        //listCollectionView.CustomSort = new NameSorter();
        //public class NameSorter : System.Collections.IComparer
        //{
        //    public int Compare(object first, object second)
        //    {
        //        return ((WbfsEntry)first).EntryName.CompareTo(((WbfsEntry)second).EntryName);
        //    }
        //}
        //
        //  Alternately myListBox.Items.SortDescriptions.Add(new SortDescription("Content", ListSortDirection.Descending));
        //  
        //
        //      Also, make sure to implement INotifyCollectionChanged



        private void button1_Click(object sender, RoutedEventArgs e)
        {
            int x = PageInkCanvas.Strokes.Count;
            FileStream fs = new FileStream("Test.isf", FileMode.Create);
            PageInkCanvas.Strokes.Save(fs);
            fs.Flush();
            fs.Close();



            //DataContractSerializer dcSerializer = new DataContractSerializer(inkCanvas1.Strokes[0].DrawingAttributes.GetType());//inkCanvas1.Strokes[0].StylusPoints.GetType());
            //fs = new FileStream("InkTestDataContract.xml", FileMode.Create);
            //dcSerializer.WriteObject(fs, inkCanvas1.Strokes[0].DrawingAttributes);
            ////dcSerializer.WriteObject(fs, inkCanvas1.Strokes[0].StylusPoints);
            ////dcSerializer.WriteObject(fs, inkCanvas1.Strokes[1].StylusPoints);
            //fs.Flush();
            //fs.Close();


            string fileName = "TestStrokes.xml";

            SerializableStrokeCollection expected = new SerializableStrokeCollection();
            StrokeCollection sc = PageInkCanvas.Strokes;
            foreach (var stroke in sc)
            {
                SerializableDrawingAttributes drawingAttr = new SerializableDrawingAttributes
                {
                    Color = stroke.DrawingAttributes.Color,
                    FitToCurve = stroke.DrawingAttributes.FitToCurve,
                    Height = stroke.DrawingAttributes.Height,
                    Width = stroke.DrawingAttributes.Width,
                    IgnorePressure = stroke.DrawingAttributes.IgnorePressure,
                    IsHighlighter = stroke.DrawingAttributes.IsHighlighter,
                    StylusTipTransform = stroke.DrawingAttributes.StylusTipTransform
                };
                switch (stroke.DrawingAttributes.StylusTip)
                {
                    case StylusTip.Ellipse:
                        drawingAttr.StylusTip = SerializableDrawingAttributes.StylusTips.Ellipse;
                        break;
                    case StylusTip.Rectangle:
                        drawingAttr.StylusTip = SerializableDrawingAttributes.StylusTips.Rectangle;
                        break;
                    default:
                        break;
                }

                SerializableStroke newStroke = new SerializableStroke { DrawingAttributes = drawingAttr };

                foreach (var stylusPoint in stroke.StylusPoints)
                {
                    newStroke.StylusPoints.Add(new SerializableStylusPoint { PressureFactor = stylusPoint.PressureFactor, X = stylusPoint.X, Y = stylusPoint.Y });
                }
                expected.Add(newStroke);
            }

            DataContractSerializer serializer = new DataContractSerializer(typeof(SerializableStrokeCollection));
            fs = new FileStream(fileName, FileMode.Create);
            serializer.WriteObject(fs, expected);
            fs.Flush();
            fs.Close();



            //foreach (var item in inkCanvas1.Strokes)
            //{
            //    foreach (var subItem in item.StylusPoints)
            //    {
            //        XmlSerializer serializer = new XmlSerializer(subItem.GetType());
            //        serializer.Serialize(new StreamWriter("Test.xml"), subItem);
            //    }
            //}

            return;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            GestureFramework.Initialize(new Windows7TouchInputProvider(), LayoutRoot);

        }

        private void NewProjectCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void NewProjectCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void OpenProjectCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog { AddExtension = true, DefaultExt = ".astprojx", Filter = "AST Project (.astprojx)|*.astprojx", FilterIndex = 0, ValidateNames = true, Title = "Open Project..." };
            if (!ofd.ShowDialog().GetValueOrDefault(false))
                return;
            ActiveSessionManager.LoadProject(ofd.FileName);

            SetupAndRenderPage(ActiveSessionManager.CurrentPage);
            MessageBox.Show("Load completed.");
        }

        private void OpenProjectCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void SaveProjectCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ActiveSessionManager.SaveCurrentPage(PageInkCanvas.Strokes);
            SaveFileDialog sfd = new SaveFileDialog { AddExtension = true, DefaultExt = ".astprojx", Filter = "AST Project (.astprojx)|*.astprojx", FilterIndex = 0, OverwritePrompt = true, ValidateNames = true, Title = "Save Project As..." };
            if (!sfd.ShowDialog().GetValueOrDefault(false))
                MessageBox.Show("Save aborted.");
            ActiveSessionManager.SaveProject(sfd.FileName);
            MessageBox.Show("Save completed.");
        }

        private void SaveProjectCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void ExportProjectCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void ExportProjectCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void ExitActiveStoryCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void ExitActiveStoryCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void DrawModeCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            PageInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
            ActiveSessionManager.ActivePenMode = PenMode.Draw;
        }

        private void DrawModeCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (PageInkCanvas.ActiveEditingMode == InkCanvasEditingMode.Ink)
                e.CanExecute = false;
            e.CanExecute = true;
        }

        private void PointEraserModeCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            PageInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
            ActiveSessionManager.ActivePenMode = PenMode.PointEraser;
        }

        private void PointEraserModeCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (PageInkCanvas.ActiveEditingMode == InkCanvasEditingMode.EraseByPoint)
                e.CanExecute = false;
            e.CanExecute = true;
        }

        private void StrokeEraserModeCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            PageInkCanvas.EditingMode = InkCanvasEditingMode.EraseByStroke;
            ActiveSessionManager.ActivePenMode = PenMode.StrokeEraser;
        }

        private void StrokeEraserModeCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (PageInkCanvas.ActiveEditingMode == InkCanvasEditingMode.EraseByStroke)
                e.CanExecute = false;
            e.CanExecute = true;
        }

        private void SelectionModeCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            PageInkCanvas.EditingMode = InkCanvasEditingMode.Select;
            ActiveSessionManager.ActivePenMode = PenMode.Selection;
        }

        private void SelectionModeCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (PageInkCanvas.ActiveEditingMode == InkCanvasEditingMode.Select)
                e.CanExecute = false;
            e.CanExecute = true;
        }

        private void CreateLinkCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void CreateLinkCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void RemoveLinkCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void RemoveLinkCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void ImportImageCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void ImportImageCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void AddPageCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ActiveSessionManager.SaveCurrentPage(PageInkCanvas.Strokes);
            ActiveSessionManager.AddNewPageToProject();
            //PageInkCanvas.Strokes.Clear();
            //PageInkCanvas.Children.Clear();
            SetupAndRenderPage(ActiveSessionManager.CurrentPage);
        }

        private void AddPageCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void DeletePageCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void DeletePageCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void CarbonCopyPageCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void CarbonCopyPageCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void RenamePageCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void RenamePageCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void SetPenColorCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void SetPenColorCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void SetCanvasSizeCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void SetCanvasSizeCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void AboutCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void UndoCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void UndoCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void RedoCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void RedoCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void BlueRibbonStyleCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            SwitchInterfaceStyle(InterfaceStyle.OfficeBlue);
        }

        private void BlueRibbonStyleCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void BlackRibbonStyleCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            SwitchInterfaceStyle(InterfaceStyle.OfficeBlack);
        }

        private void BlackRibbonStyleCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void SilverRibbonStyleCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            SwitchInterfaceStyle(InterfaceStyle.OfficeSilver);
        }

        private void SilverRibbonStyleCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void Win7RibbonStyleCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            SwitchInterfaceStyle(InterfaceStyle.Win7Ribbon);
        }

        private void Win7RibbonStyleCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void ChangeDefaultCanvasColorCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void ChangeDefaultCanvasColorCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void ChangeCurrentCanvasColorCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {

        }

        private void ChangeCurrentCanvasColorCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {

        }

        private void InterfaceMenu_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }


        /// <summary>
        /// Switches the interface style to the given style. If isRibbon is true,
        /// and style is not null the style will be applied. If style is null, the Windows 7
        /// Ribbon style will be applied. If isRibbon is false, the standard WPF style is applied.
        /// </summary>
        /// <param name="isRibbon"></param>
        /// <param name="style"></param>
        private void SwitchInterfaceStyle(InterfaceStyle newInterfaceStyle)
        {
            switch (newInterfaceStyle)
            {
                case InterfaceStyle.OfficeBlack:
                    if (Application.Current.Resources.MergedDictionaries.Count <= 0)   //No style exists in the list.
                    {
                        Application.Current.Resources.MergedDictionaries.Add(PopularApplicationSkins.Office2007Black);
                    }
                    else
                    {
                        Application.Current.Resources.MergedDictionaries[0] = PopularApplicationSkins.Office2007Black;
                    }
                    break;
                case InterfaceStyle.OfficeBlue:
                    if (Application.Current.Resources.MergedDictionaries.Count <= 0)   //No style exists in the list.
                    {
                        Application.Current.Resources.MergedDictionaries.Add(PopularApplicationSkins.Office2007Blue);
                    }
                    else
                    {
                        Application.Current.Resources.MergedDictionaries[0] = PopularApplicationSkins.Office2007Blue;

                    }
                    break;
                case InterfaceStyle.OfficeSilver:
                    if (Application.Current.Resources.MergedDictionaries.Count <= 0)   //No style exists in the list.
                    {
                        Application.Current.Resources.MergedDictionaries.Add(PopularApplicationSkins.Office2007Silver);
                    }
                    else
                    {
                        Application.Current.Resources.MergedDictionaries[0] = PopularApplicationSkins.Office2007Silver;
                    }
                    break;
                case InterfaceStyle.Win7Ribbon:
                    if (Application.Current.Resources.MergedDictionaries.Count > 0)   //No style exists in the list.
                        Application.Current.Resources.MergedDictionaries.RemoveAt(0);
                    break;
                default:
                    break;
            }

            _currentInterfaceStyle = newInterfaceStyle;
            CommandManager.InvalidateRequerySuggested();
            return;
        }

        private void CirclePenShapeToggleButton_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void RectPenShapeToggleButton_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void PageInkCanvas_Drop(object sender, DragEventArgs e)
        {
            //GestureTargetDialog gtd = new GestureTargetDialog(ActiveSessionManager);
            //if (!gtd.ShowDialog().GetValueOrDefault(false))
            //{
            //    return;
            //}

            Button emptyButton = new Button();
            emptyButton.Style = this.FindResource("HotspotButtonStyle") as Style;
            Point dropPos = e.GetPosition(PageInkCanvas);

            PrototypeElement element = new PrototypeElement { ElementType = ElementTypes.Button };

            //element.GestureTargetPageMap.Add(gtd.SelectedGesture.Identifier, gtd.SelectedPage.UnqiueId);

            //element.GestureTargetPageMap.Add(ActiveSessionManager.CommonGestureManager.KeyList[0], 2);        //Dummy code
            ActiveSessionManager.AddPrototypeElementToPage(element);

            emptyButton.Tag = element;

            Binding elementBindings = new Binding();
            elementBindings.Mode = BindingMode.TwoWay;
            elementBindings.Source = element;
            elementBindings.Path = new PropertyPath("Left");
            emptyButton.SetBinding(InkCanvas.LeftProperty, elementBindings);
            elementBindings = new Binding();
            elementBindings.Mode = BindingMode.TwoWay;
            elementBindings.Source = element;
            elementBindings.Path = new PropertyPath("Top");
            emptyButton.SetBinding(InkCanvas.TopProperty, elementBindings);
            elementBindings = new Binding();
            elementBindings.Mode = BindingMode.TwoWay;
            elementBindings.Source = element;
            elementBindings.Path = new PropertyPath("Width");
            emptyButton.SetBinding(InkCanvas.WidthProperty, elementBindings);
            elementBindings = new Binding();
            elementBindings.Mode = BindingMode.TwoWay;
            elementBindings.Source = element;
            elementBindings.Path = new PropertyPath("Height");
            emptyButton.SetBinding(InkCanvas.HeightProperty, elementBindings);
            elementBindings = new Binding();
            elementBindings.Mode = BindingMode.TwoWay;
            elementBindings.Source = element;
            elementBindings.Path = new PropertyPath("Content");
            emptyButton.SetBinding(Button.ContentProperty, elementBindings);

            emptyButton.Height = 50;
            emptyButton.Width = 100;
            emptyButton.Content = "Hotspot";
            InkCanvas.SetLeft(emptyButton, dropPos.X);
            InkCanvas.SetTop(emptyButton, dropPos.Y);
            PageInkCanvas.Children.Add(emptyButton);


            e.Handled = true;
        }

        private void PagesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PagesListBox.SelectedItem == null || PagesListBox.SelectedIndex < 0)
                return;
            ActiveSessionManager.SaveCurrentPage(PageInkCanvas.Strokes);
            DataModel.Page pageToLoad = PagesListBox.SelectedItem as DataModel.Page;
            ActiveSessionManager.LoadPage(pageToLoad);
            SetupAndRenderPage(pageToLoad);
        }

        private void SetupAndRenderPage(DataModel.Page pageToLoad)
        {
            SetupEventsPanel();
            SetupObjectsPanel(pageToLoad);
            RenderPage(pageToLoad);
        }

        private void RenderPage(DataModel.Page pageToLoad)
        {
            PageInkCanvas.Strokes.Clear();
            PageInkCanvas.Children.Clear();
            PageInkCanvas.Strokes.Add(StrokeHelper.ConvertToStrokeCollection(pageToLoad.Strokes));
            double left, top, width, height;
            String content = String.Empty;
            foreach (var item in pageToLoad.PrototypeElementDictionary.Values)
            {
                Button emptyButton = new Button();
                emptyButton.Style = (Style)this.FindResource("HotspotButtonStyle");

                left = item.Left;
                top = item.Top;
                width = item.Width;
                height = item.Height;
                content = item.Content;

                Binding elementBindings = new Binding();
                elementBindings.Mode = BindingMode.OneWayToSource;
                elementBindings.Source = item;
                elementBindings.Path = new PropertyPath("Left");
                emptyButton.SetBinding(InkCanvas.LeftProperty, elementBindings);
                elementBindings = new Binding();
                elementBindings.Mode = BindingMode.OneWayToSource;
                elementBindings.Source = item;
                elementBindings.Path = new PropertyPath("Top");
                emptyButton.SetBinding(InkCanvas.TopProperty, elementBindings);
                elementBindings = new Binding();
                elementBindings.Mode = BindingMode.OneWayToSource;
                elementBindings.Source = item;
                elementBindings.Path = new PropertyPath("Width");
                emptyButton.SetBinding(InkCanvas.WidthProperty, elementBindings);
                elementBindings = new Binding();
                elementBindings.Mode = BindingMode.OneWayToSource;
                elementBindings.Source = item;
                elementBindings.Path = new PropertyPath("Height");
                emptyButton.SetBinding(InkCanvas.HeightProperty, elementBindings);
                elementBindings = new Binding();
                elementBindings.Mode = BindingMode.OneWayToSource;
                elementBindings.Source = item;
                elementBindings.Path = new PropertyPath("Content");
                emptyButton.SetBinding(Button.ContentProperty, elementBindings);

                emptyButton.Content = content;
                InkCanvas.SetLeft(emptyButton, left);
                InkCanvas.SetTop(emptyButton, top);
                emptyButton.Width = width;
                emptyButton.Height = height;
                emptyButton.Tag = item;

                PageInkCanvas.Children.Add(emptyButton);
            }
        }


        private void SetupObjectsPanel(DataModel.Page pageToLoad)
        {
            ObjectsTreeView.Items.Clear();
            TreeViewItem rootNode = new TreeViewItem { Header = pageToLoad.Name };

            rootNode.ItemsSource = pageToLoad.PrototypeElementDictionary.ValueObservableCollection;
            rootNode.ItemTemplate = (DataTemplate)this.FindResource("ObjectsTreeViewDataTemplate");

            //var result = from item in pageToLoad.PrototypeElementDictionary.Values
            //             select new TreeViewItem { DataContext = item, Header = item.Content };
            //foreach (var item in result)
            //{
            //    rootNode.Items.Add(item);
            //}
            ObjectsTreeView.Items.Add(rootNode);
        }

        private void ObjectsTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            PrototypeElement selectedElement = e.NewValue as DataModel.PrototypeElement;
            PropertiesPropertyGrid.Instance = selectedElement;
            //WpfPropertyGrid.Data.Property prop = new WpfPropertyGrid.Data.Property(null, new PropertyDescriptor{  );

            //PropertiesPropertyGrid.Properties.Add();
        }
        private void PageInkCanvas_SelectionChanged(object sender, EventArgs e)
        {
            var elements = PageInkCanvas.GetSelectedElements();
            if (elements.Count != 1)
            {
                PropertiesPropertyGrid.Instance = null;
                SetupEventsPanel();
                return;
            }
            FrameworkElement selectedElement = elements[0] as FrameworkElement;
            PrototypeElement selectedPrototypeElement = selectedElement.Tag as PrototypeElement;
            PropertiesPropertyGrid.Instance = selectedPrototypeElement;
            SetupEventsPanel(selectedPrototypeElement);
        }
    }
}
